package jubao.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;
import com.whu.zj.VolleySingleton;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jubao.adapter.JuBaoViewAdapter;
import jubao.dto.GrassrootsOpinion;
import utils.TempUtil;
import utils.TimeUtil;

/**
 * Created by Administrator on 2016/12/22.
 */
public class JuBaoView extends UIHandler.BaseActivity {

    PullToRefreshListView pullToRefreshListView;
    ListView listView;

    JuBaoViewAdapter juBaoViewAdapter = new JuBaoViewAdapter();

    Button btn_condition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jubaoview);
        initview();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initdata();
    }

    private void initdata() {
        inithttpGet();
    }

    // 初始数据获取
    private void inithttpGet() {
        String ip = MyApplication.share().getResources().getString(R.string.IP_zj);
        String url = "http://" + ip + "/QueryGrassrootOpinion?type=2";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (!response.startsWith("["))
                    return;
                List<GrassrootsOpinion> grassrootsOpinions = JSON.parseArray(response, GrassrootsOpinion.class);
                juBaoViewAdapter.setGrassrootsOpinions(grassrootsOpinions);
                juBaoViewAdapter.notifyDataSetChanged();

                if (grassrootsOpinions.isEmpty()) {
                    Toast.makeText(MyApplication.share(), "暂无未处理举报", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MyApplication.share(), "获取失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view == btn_condition) {
                // 弹出条件
                popCondition();
            }
        }
    };

    private void popCondition() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.window_jubao_condition, null);
        final EditText et_time_begin = (EditText) layout.findViewById(R.id.id_time_begin);
        final EditText et_time_end = (EditText) layout.findViewById(R.id.id_time_end);
        final Spinner spinner = (Spinner) layout.findViewById(R.id.id_type);

        String time = TimeUtil.currentTimeSP2();
        et_time_begin.setText(TimeUtil.beforeDay(7));
        et_time_end.setText(time);


        final AlertDialog dialog =  new AlertDialog.Builder(this).setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String beginTime = et_time_begin.getText().toString();
                String endTime = et_time_end.getText().toString();
                String type = (String) spinner.getSelectedItem();

                if (!checkd(beginTime, endTime)) {
                    return;
                }

                String type_ = "0";
                if (type.equals("未处理")) {
                    type_ = "2";
                } else if (type.equals("已处理")) {
                    type_ = "1";
                } else {
                    type_ = "0";
                }
                fetchDataByCondition(beginTime, endTime, type_);
                dialog.dismiss();
            }
        });
    }

    private boolean checkd(String beginTime, String endTime) {
        if (!beginTime.matches("[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) {
            Toast.makeText(MyApplication.share(), "起始时间格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!endTime.matches("[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) {
            Toast.makeText(MyApplication.share(), "终止时间格式不正确", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    // 根据条件重新获取数据
    private void fetchDataByCondition(final String beginTime, final String endTime, final String type) {
        String IP = MyApplication.share().getResources().getString(R.string.IP_zj);
        String url = "http://" + IP + "/QueryGrassrootOpinion";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println(response);
                        if (!response.startsWith("["))
                            return;
                        List<GrassrootsOpinion> grassrootsOpinions = JSON.parseArray(response, GrassrootsOpinion.class);
                        juBaoViewAdapter.setGrassrootsOpinions(grassrootsOpinions);
                        juBaoViewAdapter.notifyDataSetChanged();

                        if (grassrootsOpinions.isEmpty()) {
                            Toast.makeText(MyApplication.share(), "无记录满足查询条件", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MyApplication.share(), "获取失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("crowdStartTime", beginTime);
                map.put("crowdEndTime", endTime);
                map.put("type", type);
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    private void initview() {
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.id_pullrefresh);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);

        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadmore();
            }
        });


        listView = pullToRefreshListView.getRefreshableView();

        listView.setAdapter(juBaoViewAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GrassrootsOpinion grassrootsOpinion = juBaoViewAdapter.getGrassrootsOpinions().get(i - 1);
                TempUtil.setObj(grassrootsOpinion);

                Intent intent = new Intent(JuBaoView.this, UpdateJuBao.class);
                JuBaoView.this.startActivity(intent);
            }
        });


        btn_condition = (Button) findViewById(R.id.id_btn_condition);
        btn_condition.setOnClickListener(onClickListener);
    }

    // 加载更多数据
    private void loadmore() {

    }
}
